<template>
  <div class="fee-log-container">
    <div class="title">患者费用信息</div>
    
    <!-- 精准搜索 -->
    <div class="search-section">
      <h3>精准搜索</h3>
      <div class="search-form">
        <div class="form-item">
          <label>病历号:</label>
          <input type="text" v-model="caseNumber" placeholder="请输入" />
        </div>
        <div class="form-item">
          <label>姓名:</label>
          <input type="text" v-model="realName" placeholder="请输入" />
        </div>
        <button class="btn-search" @click="handleSearch">搜索</button>
        <button class="btn-reset" @click="handleReset">重置</button>
      </div>
    </div>
    
    <!-- 按条件筛选 -->
    <div class="filter-section">
      <h3>按条件筛选</h3>
      <div class="filter-form">
        <div class="form-item">
          <label>消费项:</label>
          <select v-model="techName">
            <option value="">请选择</option>
            <option value="脑部CT">脑部CT</option>
            <option value="血常规">血常规</option>
            <option value="尿常规">尿常规</option>
            <!-- 可以根据实际情况添加更多选项 -->
          </select>
        </div>
        <div class="form-item">
          <label>时间范围:</label>
          <input type="date" v-model="startDate" />
          <span>-</span>
          <input type="date" v-model="endDate" />
        </div>
        <div class="form-item">
          <label>费用状态:</label>
          <select v-model="feeState">
            <option value="">请选择</option>
            <option value="已开立">已开立</option>
            <option value="已缴费">已缴费</option>
            <option value="执行完成">执行完成</option>
            <option value="已出结果">已出结果</option>
            <option value="已退费">已退费</option>
            <option value="已作废">已作废</option>
          </select>
        </div>
        <button class="btn-search" @click="handleQuery">查询</button>
        <button class="btn-reset" @click="handleFilterReset">重置</button>
      </div>
    </div>
    
    <!-- 已选择项 -->
    <div class="selected-section" v-if="selectedIds.length > 0">
      <span class="selected-info">已选择 {{ selectedIds.length }} 项</span>
    </div>
    
    <!-- 费用记录列表 -->
    <div class="table-section">
      <table class="fee-log-table">
        <thead>
          <tr>
            <th><input type="checkbox" v-model="selectAll" @change="handleSelectAll" /></th>
            <th>病历号</th>
            <th>姓名</th>
            <th>消费名称</th>
            <th>单价</th>
            <th>数量</th>
            <th>费用状态</th>
            <th>结算方式</th>
            <th>操作时间</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in feeLogList" :key="item.id">
            <td><input type="checkbox" v-model="selectedIds" :value="item.id || item.caseNumber + '-' + item.techName" /></td>
            <td>{{ item.caseNumber || '-' }}</td>
            <td>{{ item.realName || '-' }}</td>
            <td>{{ item.techName || '-' }}</td>
            <td>{{ item.techPrice || 0 }}</td>
            <td>{{ item.quantity || 1 }}</td>
            <td>
              <!-- 显示实际状态文本 -->
              <span class="status-tag" :class="getStatusClass(item.inspectionState)">
                {{ item.inspectionState || '-' }}
              </span>
            </td>
            <td>
              <label class="radio-label">
                <input type="radio" :checked="item.registMethod === '现金'" disabled />
                <span>现金</span>
              </label>
              <label class="radio-label">
                <input type="radio" :checked="item.registMethod === '银行卡'" disabled />
                <span>银行卡</span>
              </label>
              <label class="radio-label">
                <input type="radio" :checked="item.registMethod === '微信'" disabled />
                <span>微信</span>
              </label>
              <label class="radio-label">
                <input type="radio" :checked="item.registMethod === '支付宝'" disabled />
                <span>支付宝</span>
              </label>
            </td>
            <td>{{ formatDate(item.creationTime) || '-' }}</td>
          </tr>
        </tbody>
      </table>
      
      <!-- 空状态 -->
      <div class="empty-state" v-if="feeLogList.length === 0">
        暂无数据
      </div>
    </div>
    
    <!-- 批量操作和分页 -->
    <div class="batch-section">
      <div class="batch-actions">
        <button class="btn-batch-action" :disabled="selectedIds.length === 0">
          批量操作
        </button>
      </div>
      
      <!-- 分页 -->
      <div class="pagination">
        <button @click="handlePrevPage" :disabled="pageNum <= 1">上一页</button>
        <span v-for="page in totalPages" :key="page" class="page-item" :class="{ active: page === pageNum }" @click="handlePageChange(page)">
          {{ page }}
        </span>
        <button @click="handleNextPage" :disabled="pageNum >= totalPages">下一页</button>
        <select v-model="pageSize" @change="handlePageSizeChange">
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
          <option value="100">100条/页</option>
        </select>
        <span>跳至</span>
        <input type="number" v-model="jumpPage" min="1" :max="totalPages" @keyup.enter="handleJumpPage" />
        <span>页</span>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import feeLogApi from '../api/feeLog'

export default {
  name: 'FeeLog',
  setup() {
    // 搜索条件
    const caseNumber = ref('')
    const realName = ref('')
    const techName = ref('')
    const startDate = ref('')
    const endDate = ref('')
    const feeState = ref('')
    
    // 分页参数
    const pageNum = ref(1)
    const pageSize = ref(10)
    const jumpPage = ref(1)
    const total = ref(0)
    const totalPages = computed(() => Math.ceil(total.value / pageSize.value))
    
    // 数据列表
    const feeLogList = ref([])
    
    // 选中的项
    const selectedIds = ref([])
    const selectAll = ref(false)
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
    
    // 获取费用状态的样式类
    const getStatusClass = (status) => {
      switch(status) {
        case '已缴费':
          return 'status-paid';
        case '已退费':
          return 'status-refunded';
        case '已作废':
          return 'status-canceled';
        case '已出结果':
        case '执行完成':
          return 'status-completed';
        default:
          return 'status-default';
      }
    }
    
    // 获取费用记录列表
    const getFeeLogList = async () => {
      try {
        const params = {
          pageNum: pageNum.value,
          pageSize: pageSize.value,
          caseNumber: caseNumber.value,
          realName: realName.value
        }
        const res = await feeLogApi.getFeeLogList(params)
        if (res) {
          feeLogList.value = res.list || []
          total.value = res.total || 0
          // 重置选中状态
          selectedIds.value = []
          selectAll.value = false
        }
      } catch (error) {
        console.error('获取患者消费记录失败:', error)
        alert(error.message || '获取患者消费记录失败，请稍后重试')
      }
    }
    
    // 精准搜索
    const handleSearch = () => {
      pageNum.value = 1
      getFeeLogList()
    }
    
    // 重置精准搜索
    const handleReset = () => {
      caseNumber.value = ''
      realName.value = ''
      pageNum.value = 1
      getFeeLogList()
    }
    
    // 条件查询
    const handleQuery = () => {
      pageNum.value = 1
      // 注意：这里的筛选逻辑暂时只在前端实现，后端接口只支持病历号和姓名查询
      if (techName.value || feeState.value || startDate.value || endDate.value) {
        // 前端筛选逻辑
        let filteredList = [...feeLogList.value]
        
        if (techName.value) {
          filteredList = filteredList.filter(item => item.techName === techName.value)
        }
        
        if (feeState.value) {
          filteredList = filteredList.filter(item => item.inspectionState === feeState.value)
        }
        
        if (startDate.value || endDate.value) {
          filteredList = filteredList.filter(item => {
            if (!item.creationTime) return false
            
            const itemDate = new Date(item.creationTime)
            const itemDateStr = itemDate.toISOString().split('T')[0]
            
            let afterStartDate = true
            let beforeEndDate = true
            
            if (startDate.value) {
              afterStartDate = itemDateStr >= startDate.value
            }
            
            if (endDate.value) {
              beforeEndDate = itemDateStr <= endDate.value
            }
            
            return afterStartDate && beforeEndDate
          })
        }
        
        // 更新列表和总数，但不修改分页参数
        feeLogList.value = filteredList
        total.value = filteredList.length
      } else {
        getFeeLogList()
      }
    }
    
    // 重置条件筛选
    const handleFilterReset = () => {
      techName.value = ''
      startDate.value = ''
      endDate.value = ''
      feeState.value = ''
      pageNum.value = 1
      getFeeLogList()
    }
    
    // 全选/取消全选
    const handleSelectAll = () => {
      if (selectAll.value) {
        selectedIds.value = feeLogList.value.map(item => item.id || `${item.caseNumber}-${item.techName}`)
      } else {
        selectedIds.value = []
      }
    }
    
    // 分页操作
    const handlePageChange = (page) => {
      pageNum.value = page
      jumpPage.value = page
      // 如果有筛选条件，只做前端分页；否则重新请求数据
      if (techName.value || feeState.value || startDate.value || endDate.value) {
        // 前端分页逻辑已在handleQuery中处理
      } else {
        getFeeLogList()
      }
    }
    
    const handlePrevPage = () => {
      if (pageNum.value > 1) {
        pageNum.value--
        jumpPage.value = pageNum.value
        if (techName.value || feeState.value || startDate.value || endDate.value) {
          // 前端分页逻辑已在handleQuery中处理
        } else {
          getFeeLogList()
        }
      }
    }
    
    const handleNextPage = () => {
      if (pageNum.value < totalPages.value) {
        pageNum.value++
        jumpPage.value = pageNum.value
        if (techName.value || feeState.value || startDate.value || endDate.value) {
          // 前端分页逻辑已在handleQuery中处理
        } else {
          getFeeLogList()
        }
      }
    }
    
    const handlePageSizeChange = () => {
      pageNum.value = 1
      if (techName.value || feeState.value || startDate.value || endDate.value) {
        // 前端分页逻辑已在handleQuery中处理
        handleQuery()
      } else {
        getFeeLogList()
      }
    }
    
    const handleJumpPage = () => {
      let page = parseInt(jumpPage.value)
      if (isNaN(page) || page < 1) {
        page = 1
      } else if (page > totalPages.value && totalPages.value > 0) {
        page = totalPages.value
      }
      pageNum.value = page
      jumpPage.value = page
      if (techName.value || feeState.value || startDate.value || endDate.value) {
        // 前端分页逻辑已在handleQuery中处理
      } else {
        getFeeLogList()
      }
    }
    
    // 初始化加载数据
    onMounted(() => {
      getFeeLogList()
    })
    
    return {
      caseNumber,
      realName,
      techName,
      startDate,
      endDate,
      feeState,
      pageNum,
      pageSize,
      jumpPage,
      total,
      totalPages,
      feeLogList,
      selectedIds,
      selectAll,
      formatDate,
      getStatusClass,
      handleSearch,
      handleReset,
      handleQuery,
      handleFilterReset,
      handleSelectAll,
      handlePageChange,
      handlePrevPage,
      handleNextPage,
      handlePageSizeChange,
      handleJumpPage
    }
  }
}
</script>

<style scoped>
.fee-log-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.search-section, .filter-section {
  background-color: white;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-section h3, .filter-section h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
}

.search-form, .filter-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-item label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.form-item input, .form-item select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 150px;
}

.btn-search, .btn-reset, .btn-batch-action {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-search {
  background-color: #1890ff;
  color: white;
}

.btn-search:hover {
  background-color: #40a9ff;
}

.btn-reset {
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
}

.btn-reset:hover {
  background-color: #e6f7ff;
}

.btn-batch-action {
  background-color: #faad14;
  color: white;
}

.btn-batch-action:hover:not(:disabled) {
  background-color: #ffc53d;
}

.btn-batch-action:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.selected-section {
  background-color: #e6f7ff;
  padding: 10px 15px;
  margin-bottom: 15px;
  border-radius: 5px;
}

.selected-info {
  font-size: 14px;
  color: #1890ff;
}

.table-section {
  background-color: white;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow-x: auto;
}

.fee-log-table {
  width: 100%;
  border-collapse: collapse;
}

.fee-log-table th, .fee-log-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.fee-log-table th {
  background-color: #fafafa;
  font-weight: bold;
  color: #333;
  min-width: 100px;
}

.fee-log-table td {
  color: #666;
}

.fee-log-table tr:hover {
  background-color: #f5f5f5;
}

.radio-label {
  display: inline-flex;
  align-items: center;
  margin-right: 10px;
  cursor: default;
}

.radio-label input[type="radio"] {
  margin-right: 5px;
}

.empty-state {
  text-align: center;
  padding: 50px;
  color: #999;
}

.batch-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 15px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.batch-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.pagination button:hover:not(:disabled) {
  border-color: #1890ff;
  color: #1890ff;
}

.pagination button:disabled {
  cursor: not-allowed;
  color: #d9d9d9;
}

.page-item {
  padding: 6px 12px;
  cursor: pointer;
  font-size: 14px;
  border-radius: 4px;
}

.page-item.active {
  background-color: #1890ff;
  color: white;
}

.pagination select, .pagination input {
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.pagination input {
  width: 60px;
  text-align: center;
}
</style>